<template>
  <div class="main-container">
    <el-container>
      <!-- 左侧导航栏 -->
      <el-aside width="240px" class="side-menu">
        <div class="logo-container">
          <img src="../assets//images//logo.jpg" alt="社区logo" class="logo">
          <span class="system-name">东软智慧社区</span>
        </div>
        
        <el-menu
          router
          :default-active="$route.path"
          class="nav-menu"
          background-color="#304156"
          text-color="#bfcbd9"
          active-text-color="#409EFF"
          :collapse="false"
        >
          <el-menu-item index="/main/dashboard">
            <el-icon><House /></el-icon>
            <span>首页概览</span>
          </el-menu-item>
          
          <!-- 居民功能 -->
          <el-sub-menu index="1" v-if="userRole === 'resident'">
            <template #title>
              <el-icon><User /></el-icon>
              <span>个人服务</span>
            </template>
            <el-menu-item index="/main/shopping">商品购买</el-menu-item>
            <el-menu-item index="/main/parking">车位预约</el-menu-item>
            <!-- 移除访客登记菜单项 -->
            <el-menu-item index="/main/property">物业缴费</el-menu-item>
            <el-menu-item index="/main/repair">在线报修</el-menu-item>
          </el-sub-menu>

          <!-- 管理员功能 -->
          <el-sub-menu index="2" v-if="userRole === 'admin'">
            <template #title>
              <el-icon><Setting /></el-icon>
              <span>后台管理</span>
            </template>
            <el-menu-item index="/admin/user-mgmt">用户管理</el-menu-item>
            <el-menu-item index="/admin/parking-mgmt">车位管理</el-menu-item>
            <el-menu-item index="/admin/fee-mgmt">费用管理</el-menu-item>
            <el-menu-item index="/admin/repair-mgmt">报修管理</el-menu-item>
            <el-menu-item index="/admin/visitor-approval">访客审批</el-menu-item>
          </el-sub-menu>
        </el-menu>
      </el-aside>

      <!-- 右侧内容区 -->
      <el-container>
        <el-header class="main-header">
          <div class="header-right">
            <el-dropdown>
              <span class="user-info">
                <el-avatar :size="32" :src="userAvatar"/>
                <span class="username">{{ userName }}</span>
                <el-icon><ArrowDown /></el-icon>
              </span>
              <template #dropdown>
                <el-dropdown-menu>
                  <el-dropdown-item @click="handleProfile">
                    <el-icon><User /></el-icon>个人中心
                  </el-dropdown-item>
                  <el-dropdown-item @click="handleLogout">
                    <el-icon><SwitchButton /></el-icon>退出登录
                  </el-dropdown-item>
                </el-dropdown-menu>
              </template>
            </el-dropdown>
          </div>
        </el-header>
        
        <el-main class="main-content">
          <router-view></router-view>
        </el-main>
      </el-container>
    </el-container>
  </div>
</template>

<script setup>
import { ref, onMounted } from 'vue'
import { useRouter } from 'vue-router'
import { House, User, Setting, ArrowDown, SwitchButton } from '@element-plus/icons-vue'
import { ElMessage } from 'element-plus'
import { getUserInfo } from '../api/api' // 确保已导入 getUserInfo 接口

const router = useRouter()
const userInfo = JSON.parse(localStorage.getItem('userInfo') || '{}')
const userRole = ref(localStorage.getItem('role') || userInfo.role || 'guest')
const userName = ref(userInfo.username || '游客')
const userAvatar = ref('')

console.log('MainLayout - 用户角色:', userRole.value)
console.log('MainLayout - 用户信息:', userInfo)

const handleLogout = () => {
  // 清除所有用户相关的localStorage项，但保留"记住我"相关的信息
  localStorage.removeItem('userInfo')
  localStorage.removeItem('token')
  localStorage.removeItem('userId')
  localStorage.removeItem('role')
  localStorage.removeItem('cartId')
  
  // 注意：不清除savedUsername和savedPassword，以便下次登录时自动填充
  
  router.push('/login')
}

// 处理个人中心点击
const handleProfile = async () => {
  try {
    const userId = userInfo.userId
    if (!userId) {
      ElMessage.error('用户信息不存在')
      return
    }
    
    // 调用获取用户信息接口
    const res = await getUserInfo(userId)
    if (res.code === 200 && res.data) {
      // 更新本地存储的用户信息
      const userData = res.data
      const updatedUserInfo = {
        userId: userData.userId,
        username: userData.username,
        role: userData.role,
        email: userData.email,
        phoneNumber: userData.phoneNumber,
        createdAt: userData.createdAt,
        updatedAt: userData.updatedAt
      }
      localStorage.setItem('userInfo', JSON.stringify(updatedUserInfo))
      
      // 跳转到个人中心页面
      router.push('/main/profile')
    } else {
      ElMessage.error(res?.message || '获取用户信息失败')
    }
  } catch (error) {
    console.error('获取用户信息错误:', error)
    ElMessage.error('获取用户信息失败')
  }
}
</script>

<style scoped>
.main-container {
  height: 100vh;
  background: #f0f2f5;
}

.side-menu {
  background: #304156;
  transition: width 0.3s;
}

.logo-container {
  height: 60px;
  display: flex;
  align-items: center;
  padding: 0 20px;
  background: #2b2f3a;
}

.logo {
  width: 32px;
  height: 32px;
  margin-right: 12px;
}

.system-name {
  color: #fff;
  font-size: 18px;
  font-weight: 600;
}

.nav-menu {
  border-right: none;
}

.main-header {
  display: flex;
  align-items: center;
  justify-content: flex-end;
  height: 60px;
  background: #fff;
  box-shadow: 0 1px 4px rgba(0,21,41,.08);
}

.user-info {
  display: flex;
  align-items: center;
  cursor: pointer;
}

.username {
  margin: 0 8px;
  font-size: 14px;
}

.main-content {
  padding: 20px;
  background: #f0f2f5;
  min-height: calc(100vh - 60px);
}
</style>